const ul = document.querySelector('ul');
const checkout = document.querySelector(".checkout")
const totalPrice = document.querySelector(".total-price")

const currentUser = localStorage.getItem("currentUser");
const commoditys = JSON.parse(localStorage.getItem("commoditys"));
const userInfo = JSON.parse(localStorage.getItem("userInfo"));

function show() {
    if (currentUser === null) {
        alert("请先登录")
        return;
    }
    
    //页面实现
    const userIdx = userInfo.findIndex(item => item.username === currentUser)
    const shopArr = userInfo[userIdx].shop || [];
    shopArr.forEach(item => {
        for (let key in item) { // key: 商品名  value: 商品数量
            let value = item[key];
            const id = commoditys.findIndex(commodity => commodity.name === key);
            let img = commoditys[id].image;
            let price = commoditys[id].price;
            let li = document.createElement("li");
            li.innerHTML = `
                <img src="${img}">
                <div class="cart-info">
                    <h4 class="name">${key}</h4>
                    <h4 class="price">￥${price}</h4>
                </div>
                <button>-</button>
                <div>${value}</div>
                <button>+</button>
                <button>删除</button>
                `
            ul.appendChild(li);
            allPrice();
        }
    })

    if (shopArr.length === 0) {
        let li = document.createElement("li");
        li.textContent = "购物车中什么都没有哦~";
        ul.appendChild(li);
    }
}
show();

// 加减商品数量
ul.addEventListener("click", function (e) {
    if (e.target.nodeName !== "BUTTON") return;

    const li = e.target.closest("li");
    const name = li.querySelector(".name").textContent;   // 商品名
    const userIdx = userInfo.findIndex(u => u.username === currentUser);
    const shopArr = userInfo[userIdx].shop;

    const goodsIdx = shopArr.findIndex(g => g[name] !== undefined);
    if (goodsIdx === -1) return;

    let goodsNum = shopArr[goodsIdx][name];

    /* 1. 减少数量 */
    if (e.target.textContent === "-") {
        goodsNum--;
        if (goodsNum <= 0) {
            shopArr.splice(goodsIdx, 1);
            li.remove();
        } else {
            shopArr[goodsIdx][name] = goodsNum;
            li.children[3].textContent = goodsNum;
        }
        allPrice()
    }

    /* 2. 增加数量 */
    if (e.target.textContent === "+") {
        goodsNum++;
        shopArr[goodsIdx][name] = goodsNum;
        li.children[3].textContent = goodsNum;
        allPrice()
    }

    /* 3. 删除商品 */
    if (e.target.textContent === "删除") {
        shopArr.splice(goodsIdx, 1);
        li.remove();
        allPrice()
    }

    localStorage.setItem("userInfo", JSON.stringify(userInfo));

    // 若购物车为空，可选提示或隐藏结算区
    if (shopArr.length === 0) {
        let li = document.createElement("li");
        li.textContent = "购物车中什么都没有哦~";
        ul.appendChild(li);
    }

    num();
});

// 计算总价
function allPrice() {
    const userIdx = userInfo.findIndex(u => u.username === currentUser);
    const shopArr = userInfo[userIdx].shop || [];
    let total = 0;

    shopArr.forEach(item => {
        for (let name in item) {
            const id  = commoditys.findIndex(c => c.name === name);
            if (id !== -1) total += commoditys[id].price * item[name];
        }
    });

    totalPrice.textContent = "总计：￥" + (total.toFixed(2) ? total.toFixed(2) : 0.00);
}
allPrice();

// 结算
checkout.addEventListener("click", function () {
    const userIdx = userInfo.findIndex(u => u.username === currentUser);
    const shopArr = userInfo[userIdx].shop;
    if (currentUser === null) {
        alert("请先登录")
        return;
    }
    if (shopArr.length === 0) {
        alert("先去逛逛吧~")
        return;
    } else {
        shopArr.splice(0, shopArr.length);
        localStorage.setItem("userInfo", JSON.stringify(userInfo));
        for (let i = 0; ul.children.length != 0; i++) {
            ul.removeChild(ul.children[0]);
        }
        let li = document.createElement("li");
        li.textContent = "购物车中什么都没有哦~";
        ul.appendChild(li);
        num();
        allPrice();
        alert("支付成功");
    }
});

// 购物车数量
function num() {
    const span = document.querySelector('.top:nth-child(3) span');
    const userIdx = userInfo.findIndex(u => u.username === currentUser);
    const shopArr = userInfo[userIdx].shop;
    let arr = [];
    shopArr.forEach(n => {
        for (let key in n) {
            let value = n[key];
            arr.push(value);
        }
    })
    number = arr.reduce((acc, cur) => acc + cur, 0)
    if (number) {
        span.style.display = "inline-block";
        span.innerText = `${number}`;
    } else {
        span.style.display = "none";
    }
};
num();